package com.mokairui.share_model__routines.squential_control.fixed_sequence;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description 固定顺序 - wait notify版本
 *              线程的顺序本来是根据谁先获取到锁谁就先执行的, 修改为固定顺序使用 wait notify版本
 * @Author Mokairui
 * @Since 2021/10/4
 */
@Slf4j(topic = "c.fixedSequence")
public class FixedSequenceWaitNotify {
    // 用来同步的对象
    static Object monitor = new Object();
    // t2 标记, 标记t2线程是否执行过, 先让t2执行
    static boolean t2runner = false;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            synchronized (monitor) {
                if (!t2runner) {
                    try {
                        monitor.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("t1线程执行完了...");
            }
        });

        Thread t2 = new Thread(() -> {
            synchronized (monitor) {
                t2runner = true;
                log.debug("t2线程执行完了...");
                monitor.notifyAll();
            }
        });

        t1.start();
        t2.start();
    }
}
